package model.geo;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;

import model.persistence.DBMS;

/**
 * 
 * @author Giuseppe Fusco (fusgius19@gmail.com)
 *
 */
public class GeoController implements GeoControllerInterface {

	private Object map;
	private Coord ref;
	
	public GeoController(DBMS dbms){
		map = (Mappa)retrieveMap(dbms);
	}

	public void setRef(Coord ref) {
		this.ref = ref;
	}
	
	/**
	 * @see model.geo.GeoControllerInterface#isValidGeoPosition()
	 */
	public boolean isValidGeoPosition() {
		for(Coord c: ((Mappa)map).getPossibleCoords())
			if(c.getLatitudine()==ref.getLatitudine() && c.getLongitudine()==ref.getLongitudine())
				return true;
		return false;
	}

	public Object retrieveMap(DBMS dbms) {
		try {
			Mappa m = new Mappa();
			ArrayList<Coord> list = new ArrayList<Coord>();
			BufferedReader buf = new BufferedReader(new InputStreamReader(new FileInputStream("mappa.txt")));
			String line = buf.readLine();
			while(line!=null){
				StringTokenizer tok = new StringTokenizer(line,".");
				Coord c= new Coord();
				c.setLatitudine(Double.parseDouble(tok.nextToken()));
				c.setLongitudine(Double.parseDouble(tok.nextToken()));
				list.add(c);
				line = buf.readLine();
			}
			buf.close();
			m.setPossibleCoords(list);
			return m;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			try {
				throw new FileNotFoundException();
			} catch (FileNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			try {
				throw new IOException();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		return new Mappa();
	}

}
